# from urllib import response
# from wsgiref import headers
# from twisted.internet.defer import returnValue
# from twisted.spread.pb import respond
import requests
from lxml import etree
from bs4 import BeautifulSoup
import re


class Login():
    def __init__(self) -> None:
        self.headers = {
            'User-Agent': 'Mozilla/s.o (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Sa ari/537.36',
            'Referer': 'https://gitee.com/',
            'Host': 'gitee.com',
        }
        
        self.login_url = 'https://gitee.com/login'
        self.post_url = 'https://gitee.com/check_user_login'
        self.repositories_url = 'https://gitee.com/api/v3/internal/my_resources'
        self.session = requests.Session() # 维持会话，自动处理cookies
        

    def token(self):
        r = self.session.get(self.login_url,headers=self.headers)
        html = etree.HTML(r.text)
        # token = html.xpath('//*[@id="new_user"]/div[1]/input[2]/@value')[0] 
        token = html.xpath('//div/input[2]/@value')[0]   
        print('token:',token)
        print(self.session)
        return token

    def login(self, email, password):
        post_data = { # 除了user直接显示在表单中，其余在源代码中查找，form中相关元素
            'utf8':'✓', 
            'authenticity_token': self.token(),
            'user[login]': email,  
            'user[password]': password,
            'commit':'登 录',
            # 'cache-control' : 'no-cache'
        }
        response = self.session.post(self.login_url, data=post_data, headers=self.headers) # 登录检查
        #print(response) # 返回 200
        # print(response.text)
        # response = self.session.get(self.repositories_url,headers=self.headers)
        #print(response.status_code)
        # print(response.headers)
        # print(response.text)
        # with open ('./login/gitee_html_loged.txt','w',encoding='utf-8') as f:
        #     f.write(response.text)
        if response.status_code == 200:
            self.projects(response.text)
        else:
            print('error')
        
    def projects(self,html):
        # html = etree.HTML(html)
        # pj = html.xpath('//*[@id="rc-users__container"]/div[1]/div[2]/div/div[1]/div[2]/div[3]/div/div[3]/div[2]/div/div[1]/div/a/@href')    
        # pj = html.xpath('//*[@id="rc-users__container"]/div[1]/div[2]/div/div[1]/div[2]/div[3]/div/div[3]/div[2]/div/div[2]/@data-path') 
        pattern = re.compile("<div class='item project-item' data-path='ybmyun/(.*?)'>", re.S)
        pj = re.findall(pattern, html)
        print(pj)
        




if __name__ == "__main__":
    giteelogin = Login()
    giteelogin.login(email='',password='')


